<template>
  <div class="app-layout">
    <div class="sidebar">
      <div class="logo-section">
        <img src="@/assets/medical/logo.png" alt="小智" width="160" height="160"/>
        <span class="logo-text">小智（医疗版）</span>
      </div>
      <el-button class="new-chat-button" @click="newChat">
        <i class="fa-solid fa-plus"></i>
        &nbsp;新会话
      </el-button>
    </div>
    <div class="main-content">
      <div class="chat-container">
        <div class="message-list" ref="messageListRef">
          <div
            v-for="(message, index) in messages"
            :key="index"
            :class="
              message.isUser ? 'message user-message' : 'message bot-message'
            "
          >
            <!-- 会话图标 -->
            <i
              :class="
                message.isUser
                  ? 'fa-solid fa-user message-icon'
                  : 'fa-solid fa-robot message-icon'
              "
            ></i>
            <!-- 会话内容 -->
            <span>
              <span v-html="message.content"></span>
              <!-- loading -->
              <span
                class="loading-dots"
                v-if="message.isThinking || message.isTyping"
              >
                <span class="dot"></span>
                <span class="dot"></span>
              </span>
            </span>
          </div>
        </div>
        <div class="input-container">
          <el-input
            v-model="inputMessage"
            placeholder="请输入消息"
            @keyup.enter="sendMessage"
          ></el-input>
          <el-button @click="sendMessage" :disabled="isSending" type="primary"
          >发送
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {streamChat} from "@/api/langchain/medical"
import {v4 as uuidv4} from 'uuid'

export default {
  name: 'MedicalChat',
  data() {
    return {
      inputMessage: '',
      isSending: false,
      uuid: '',
      messages: [],
    }
  },
  mounted() {
    this.initUUID()
    this.sendRequest('你好')
  },
  methods: {
    scrollToBottom() {
      this.$nextTick(() => {
        const el = this.$refs.messageListRef
        if (el) el.scrollTop = el.scrollHeight
      })
    },
    sendMessage() {
      if (this.inputMessage.trim()) {
        this.sendRequest(this.inputMessage.trim())
        this.inputMessage = ''
      }
    },
    sendRequest(message) {
      this.isSending = true

      this.messages.push({
        isUser: true,
        content: this.escapeHTML(message),
        isTyping: false,
      })

      const botMsg = {
        isUser: false,
        content: '',
        isTyping: true,
      }
      this.messages.push(botMsg)

      const lastMsg = this.messages[this.messages.length - 1]
      this.scrollToBottom()

      streamChat(
        {
          memoryId: this.uuid,
          userMessage: message
          // userMessage: message + ' /no_think'
        },
        (e) => {
          const response = e?.target?.responseText || ''
          const newText = response.substring(lastMsg.content.length)
          lastMsg.content += this.escapeHTML(newText)
          this.scrollToBottom()
        }
      ).then(() => {
        lastMsg.isTyping = false
        this.isSending = false
      }).catch(() => {
        lastMsg.content = '请求失败，请重试'
        lastMsg.isTyping = false
        this.isSending = false
      })


    },
    escapeHTML(text) {
      return text
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/\\n/g, '<br>')
        .replace(/\\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;')
    },
    initUUID() {
      let storedUUID = localStorage.getItem('user_uuid')
      if (!storedUUID) {
        storedUUID = uuidv4()
        localStorage.setItem('user_uuid', storedUUID)
      }
      this.uuid = storedUUID
    },
    newChat() {
      localStorage.removeItem('user_uuid')
      window.location.reload()
    }
  }
}
</script>

<style scoped>
.app-layout {
  display: flex;
  height: 100vh;
}

.sidebar {
  width: 200px;
  background-color: #f4f4f9;
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.logo-section {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.logo-text {
  font-size: 18px;
  font-weight: bold;
  margin-top: 10px;
}

.new-chat-button {
  width: 100%;
  margin-top: 20px;
}

.main-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  background-color: #fff;
  margin-bottom: 10px;
  display: flex;
  flex-direction: column;
}

.message {
  margin-bottom: 10px;
  padding: 10px;
  border-radius: 4px;
  display: flex;
  /* align-items: center; */
}

.user-message {
  max-width: 70%;
  background-color: #e1f5fe;
  align-self: flex-end;
  flex-direction: row-reverse;
}

.bot-message {
  max-width: 100%;
  background-color: #f1f8e9;
  align-self: flex-start;
}

.message-icon {
  margin: 0 10px;
  font-size: 1.2em;
}

.loading-dots {
  padding-left: 5px;
}

.dot {
  display: inline-block;
  margin-left: 5px;
  width: 8px;
  height: 8px;
  background-color: #000000;
  border-radius: 50%;
  animation: pulse 1.2s infinite ease-in-out both;
}

.dot:nth-child(2) {
  animation-delay: -0.6s;
}

@keyframes pulse {
  0%,
  100% {
    transform: scale(0.6);
    opacity: 0.4;
  }

  50% {
    transform: scale(1);
    opacity: 1;
  }
}

.input-container {
  display: flex;
}

.input-container .el-input {
  flex: 1;
  margin-right: 10px;
}

/* 媒体查询，当设备宽度小于等于 768px 时应用以下样式 */
@media (max-width: 768px) {
  .main-content {
    padding: 10px 0 10px 0;
  }

  .app-layout {
    flex-direction: column;
  }

  .sidebar {
    /* display: none; */
    width: 100%;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
  }

  .logo-section {
    flex-direction: row;
    align-items: center;
  }

  .logo-text {
    font-size: 20px;
  }

  .logo-section img {
    width: 40px;
    height: 40px;
  }

  .new-chat-button {
    margin-right: 30px;
    width: auto;
    margin-top: 5px;
  }
}

/* 媒体查询，当设备宽度大于 768px 时应用原来的样式 */
@media (min-width: 769px) {
  .main-content {
    padding: 0 0 10px 10px;
  }

  .app-layout {
    display: flex;
    height: 100vh;
  }

  .sidebar {
    width: 200px;
    background-color: #f4f4f9;
    padding: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .logo-section {
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .logo-text {
    font-size: 18px;
    font-weight: bold;
    margin-top: 10px;
  }

  .new-chat-button {
    width: 100%;
    margin-top: 20px;
  }
}
</style>
